import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:note/common/common.dart';
import 'package:note/common/tools.dart';
import 'package:note/pages/edit_note_page/components/editToolBar.dart';
import 'package:note/widgets/BasePage.dart';
import 'package:note/widgets/formFields.dart';
import 'package:note/widgets/scrollBarView.dart';

import '../../widgets/markdown.dart';
import '../../widgets/showPhotoView.dart';
import 'logic.dart';

class EditNotePage extends StatelessWidget {
  EditNotePage({Key? key}) : super(key: key);

  final logic = Get.put(EditNotePageLogic());
  final state = Get.find<EditNotePageLogic>().state;

  @override
  Widget build(BuildContext context) {
    return BasePage(
      child: WillPopScope(
        onWillPop: logic.willLeaveEdit,
        child: GestureDetector(
          onTap: () => logic.cancelFocus(context),
          child: Scaffold(
            appBar: AppBar(
              title: const Text(Strings.editNoteTitle),
              backgroundColor: Styles.backgroundColor,
              foregroundColor: Styles.mainThemeColor,
              actions: [
                IconButton(
                    onPressed: logic.onSave, icon: const Icon(Icons.save))
              ],
            ),
            body: Row(
              children: [
                ///预显示内容
                Tools.isTabletLandscape(context)
                    ? Expanded(
                        flex: 1,
                        child: SizedBox(
                          height: MediaQuery.of(context).size.height,
                          child: DefaultScrollBarView(
                            controller: state.showScrollController,
                            child: showEditData(),
                          ),
                        ),
                      )
                    : Container(),

                ///分割线
                Container(
                  width: 1,
                  height: MediaQuery.of(context).size.height,
                  color: Styles.shadowColor,
                ),

                ///编辑区
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      Expanded(
                        child: GestureDetector(
                          onTap: () => logic.onBody(context),
                          child: Form(
                            child: DefaultScrollBarView(
                              controller: state.scrollController,
                              padding:
                                  const EdgeInsets.only(left: 15, right: 15),
                              child: editData(),
                            ),
                          ),
                        ),
                      ),
                      EditToolBar(
                        state: state,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // //悬浮按钮
            // floatingActionButton: Obx(() {
            //   return Visibility(
            //     visible: state.isOverSize.value,
            //     child: Obx(() {
            //       return GestureDetector(
            //         onTap: state.inUp.value ? logic.onToBottom : logic.onToTop,
            //         child: Container(
            //           width: 50,
            //           height: 50,
            //           margin: const EdgeInsets.only(right: 10, bottom: 40),
            //           decoration: const BoxDecoration(
            //               color: Styles.mainThemeColor,
            //               boxShadow: [
            //                 BoxShadow(color: Styles.shadowColor, blurRadius: 5)
            //               ],
            //               borderRadius: BorderRadius.all(Radius.circular(25))),
            //           child: state.inUp.value
            //               ? const Icon(
            //                   Icons.vertical_align_bottom,
            //                   color: Styles.lightColor,
            //                   size: 30,
            //                 )
            //               : const Icon(
            //                   Icons.vertical_align_top,
            //                   color: Styles.lightColor,
            //                   size: 30,
            //                 ),
            //         ),
            //       );
            //     }),
            //   );
            // }),
          ),
        ),
      ),
    );
  }

  Widget showEditData() {
    return Obx(() {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //图片
          Obx(() {
            if (state.images.isEmpty) {
              return Container();
            }
            return Container(
              height: 200,
              color: Styles.backgroundColor,
              child: Swiper(
                itemCount: state.images.length,
                controller: state.swiperController,
                loop: false,
                pagination: const SwiperPagination(
                    builder: DotSwiperPaginationBuilder(
                        size: 6,
                        activeSize: 12,
                        color: Styles.backgroundColor,
                        activeColor: Styles.mainThemeColor)),
                itemBuilder: (BuildContext context, int index) {
                  return Image(image: FileImage(state.images[index]));
                },
                onTap: (index) {
                  Get.to(ShowPhotoGallery(images: state.images, index: index))
                      ?.then((value) {
                    state.swiperController.move(value, animation: false);
                  });
                },
                onIndexChanged: (index) {
                  state.swiperController.index = index;
                },
              ),
            );
          }),
          //标题
          Padding(
            padding: const EdgeInsets.only(left: 16.0, top: 10),
            child: Text(
              state.showTitle.value,
              style: Styles.textStyleMedium(30),
            ),
          ),
          //内容
          MyMarkDownBody(
            data: state.showData.value,
            padding: const EdgeInsets.fromLTRB(15, 8, 15, 8),
          ),
          //时间
          Align(
              alignment: Alignment.centerRight,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  DateTimeToString.toYYMMDDHSN(state.note.editTime),
                  style: Styles.textTransparentNormal(15),
                ),
              )),
        ],
      );
    });
  }

  Widget editData() {
    return Column(
      children: [
        DefaultFormField(
          style: Styles.textStyleBold(30),
          textEditingController: state.titleController,
          focusNode: state.titleFocusNode,
          hintText: Strings.noteTitle,
          textInputAction: TextInputAction.next,
          hintStyle: Styles.textTransparentNormal(30),
          maxLines: 3,
          onChange: logic.onChangeTitle,
        ),
        Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(left: 15.0),
              child: Text(
                DateTimeToString.toYYMMDDHSN(state.note.editTime),
                style: Styles.textTransparentNormal(12),
              ),
            )),
        DefaultFormField(
          style: Styles.textStyleNormal(20),
          textEditingController: state.contentController,
          focusNode: state.contentFocusNode,
          hintText: Strings.noteContent,
          maxLines: 10000,
          onChange: logic.onChangeData,
        ),
        Align(
          alignment: Alignment.bottomRight,
          child: Obx(
            () {
              if (state.contentLength.value == 0) {
                return Container();
              }
              return Text(
                '共${state.contentLength.value.toString()}个字',
                style: Styles.textTransparentNormal(12),
              );
            },
          ),
        ),
        Obx(() {
          return SizedBox(
            height: 100,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: [
                addPhotoContainer(),
                ...List.generate(
                  state.images.length,
                  (index) {
                    return photoCard(index);
                  },
                ),
              ],
            ),
          );
        }),
        const SizedBox(
          height: 10,
        ),
        Obx(() {
          if (state.images.isEmpty) {
            return Container();
          }
          return Align(
            alignment: Alignment.centerRight,
            child: Text(
              '已选择${state.images.length}张图片',
              style: Styles.textTransparentNormal(10),
            ),
          );
        })
      ],
    );
  }

  Widget addPhotoContainer() {
    return GestureDetector(
      onTap: logic.onAddPhoto,
      child: Container(
        width: 100,
        height: 100,
        alignment: Alignment.center,
        margin: const EdgeInsets.only(right: 10),
        decoration: const BoxDecoration(
          color: Styles.backgroundColor,
          borderRadius: BorderRadius.all(Radius.circular(20)),
        ),
        child: const Icon(
          Icons.add_photo_alternate,
          color: Styles.mainThemeColor,
          size: 40,
        ),
      ),
    );
  }

  Widget photoCard(int index) {
    return GestureDetector(
      onTap: () => logic.onPhoto(index),
      child: Stack(alignment: Alignment.topRight, children: [
        Container(
          width: 100,
          height: 100,
          margin: const EdgeInsets.only(right: 10),
          decoration: BoxDecoration(
            color: Styles.backgroundColor,
            border: Border.all(color: Styles.mainThemeColor),
            borderRadius: const BorderRadius.all(Radius.circular(20)),
          ),
          child: File(state.images[index].path).existsSync()
              ? ClipRRect(
                  borderRadius: const BorderRadius.all(Radius.circular(20)),
                  child: Image(
                    image: FileImage(
                      state.images[index],
                    ),
                    fit: BoxFit.cover,
                  ),
                )
              : const Icon(
                  Icons.error,
                  color: Styles.mainThemeColor,
                ),
        ),
        GestureDetector(
          onTap: () => logic.onDeletePhoto(index),
          child: const Icon(
            Icons.cancel_outlined,
            color: Styles.mainThemeColor,
          ),
        )
      ]),
    );
  }
}
